package com.ruoyi.common.config.mybatis;


import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.parser.JsqlParserSupport;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.delete.Delete;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;

import java.sql.Connection;

/**
 * @Classname DeleteInterceptor
 * @Author: sunluquan
 * @Date: 2021/12/17 17:02
 * @Description TODO
 * 处理删除逻辑 将删除的信息保存值通用备份表中
 */
@Slf4j
public class DeleteInnerInterceptor extends JsqlParserSupport implements InnerInterceptor {

    /**
     * {@link StatementHandler#prepare(Connection, Integer)} 操作前置处理
     * <p>
     * 修改的sql语句已经准备好执行  这时需要将删除的数据保存
     *
     * @param sh                 StatementHandler(可能是代理对象)
     * @param connection         Connection
     * @param transactionTimeout transactionTimeout
     */
    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {

        PluginUtils.MPStatementHandler mpStatementHandler = PluginUtils.mpStatementHandler(sh);
        MappedStatement ms = mpStatementHandler.mappedStatement();
        SqlCommandType sct = ms.getSqlCommandType();
        //只处理删除
        if (sct == SqlCommandType.DELETE) {
            BoundSql boundSql = mpStatementHandler.boundSql();
            String originalSql = boundSql.getSql();
            parserSingle(originalSql, connection);
        }
    }

    @Override
    protected void processDelete(Delete delete, int index, String sql, Object obj) {

        log.info("DeleteInnerInterceptor --- sql:{}",sql);

    }
}
